import os
import subprocess
import re
import platform
from typing import Dict, Tuple, Optional

# 全局配置 - 安卓环境要求（移除了版本限制）
ENV_CONFIG = {
    "required": {
        "java": {
            "download": "<url id=\"d287fhiej2dh7lsuv8eg\" type=\"url\" status=\"parsed\" title=\"Adoptium\" wc=\"202\">https://adoptium.net/temurin/releases/</url> ",
            "description": "Java Development Kit (JDK)"
        },
        "android_sdk": {
            "description": "Android SDK命令行工具"
        },
        "build_tools": {
            "download": "使用Android SDK Manager安装",
            "description": "Android Build Tools"
        },
        "platform_tools": {
            "download": "<url id=\"d287fhiej2dh7lsuv8f0\" type=\"url\" status=\"parsed\" title=\"SDK Platform Tools release notes\" wc=\"69417\">https://developer.android.com/studio/releases/platform-tools</url> ",
            "description": "Android Platform Tools (包含adb)"
        },
        "gradle": {
            "download": "<url id=\"d287fhiej2dh7lsuv8fg\" type=\"url\" status=\"parsed\" title=\"Gradle | Installation\" wc=\"4369\">https://gradle.org/install/</url> ",
            "description": "Gradle 构建工具"
        }
    }
}

def get_android_sdk_info() -> Optional[Dict[str, str]]:
    """获取 Android SDK 信息（仅检测存在性，不限制版本）"""
    # 优先从环境变量获取
    sdk_path = os.environ.get("ANDROID_HOME")

    # 环境变量未设置时，尝试默认路径
    if not sdk_path:
        default_paths = [
            os.path.join(os.path.expanduser("~"), "Android", "Sdk"),  # Windows/macOS 默认
            "/usr/local/android-sdk"  # Linux 常见路径
        ]
        for path in default_paths:
            # 检查 SDK 核心目录（platform-tools/adb）是否存在
            if os.path.exists(
                    os.path.join(path, "platform-tools", "adb.exe" if platform.system() == "Windows" else "adb")):
                sdk_path = path
                break
        if not sdk_path:
            return {"error": "未设置 ANDROID_HOME 环境变量，且未找到默认 SDK 路径"}

    # 验证 SDK 路径有效性
    if not os.path.exists(sdk_path):
        return {"error": f"Android SDK 路径不存在: {sdk_path}"}

    # 尝试获取 SDK 版本（可选）
    version = "未知版本"
    try:
        sdkmanager = "sdkmanager.bat" if platform.system() == "Windows" else "sdkmanager"
        # 兼容新版 SDK 目录结构（cmdline-tools/latest/bin）
        sdkmanager_path = os.path.join(sdk_path, "cmdline-tools", "latest", "bin", sdkmanager)
        if not os.path.exists(sdkmanager_path):
            # 回退到老版路径（tools/bin）
            sdkmanager_path = os.path.join(sdk_path, "tools", "bin", sdkmanager)

        if os.path.exists(sdkmanager_path):
            result = subprocess.run(
                [sdkmanager_path, "--version"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True
            )
            if result.returncode == 0:
                version_match = re.search(r"(\d+\.\d+\.\d+)", result.stdout)
                if version_match:
                    version = version_match.group(1)
    except Exception:
        pass  # 版本获取失败不影响整体检测

    return {
        "name": "Android SDK",
        "version": version,
        "path": sdk_path
    }

def check_java_environment() -> Tuple[bool, str, str, str]:
    """检测Java环境（仅检测存在性，不检查版本）"""
    try:
        # 检查java命令是否存在
        java_cmd = "java.exe" if platform.system() == "Windows" else "java"
        result = subprocess.run(
            [java_cmd, "-version"],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True
        )
        if result.returncode != 0:
            return (False, "", "", "未找到Java环境，请安装JDK")

        # 获取安装路径
        path_result = subprocess.run(
            ["where" if platform.system() == "Windows" else "which", java_cmd],
            stdout=subprocess.PIPE,
            text=True
        )
        path = path_result.stdout.strip().rsplit(os.sep, 2)[0]  # 提取JDK根目录

        # 解析版本
        version_line = [line for line in result.stdout.splitlines() if "version" in line][0]
        version_match = re.search(r'"(\d+\.\d+\.\d+)"', version_line)
        if version_match:
            version = version_match.group(1)
        else:
            version = "未知版本"

        return (True, version, path, "Java环境正常")
    except Exception as e:
        return (False, "", "", f"Java检测异常: {str(e)}")

def check_adb_environment() -> Tuple[bool, str, str, str]:
    """检测ADB环境（仅检测存在性，不检查版本）"""
    try:
        adb_cmd = "adb.exe" if platform.system() == "Windows" else "adb"
        result = subprocess.run(
            [adb_cmd, "--version"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        if result.returncode != 0:
            return (False, "", "", "未找到adb工具，请安装Android Platform Tools")

        # 获取安装路径
        path_result = subprocess.run(
            ["where" if platform.system() == "Windows" else "which", adb_cmd],
            stdout=subprocess.PIPE,
            text=True
        )
        path = path_result.stdout.strip()

        # 解析版本
        version_match = re.search(r"Version\s+(\d+\.\d+\.\d+)", result.stdout)
        if version_match:
            version = version_match.group(1)
        else:
            version = "未知版本"

        return (True, version, path, "ADB环境正常")
    except Exception as e:
        return (False, "", "", f"ADB检测异常: {str(e)}")

def check_gradle_environment() -> Tuple[bool, str, str, str]:
    """检测Gradle环境 - 仅检测存在性"""
    try:
        gradle_cmd = "gradle.bat" if platform.system() == "Windows" else "gradle"
        result = subprocess.run(
            [gradle_cmd, "--version"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        if result.returncode != 0:
            return (False, "", "", "未找到Gradle环境，请安装或配置环境变量")

        # 获取安装路径
        path_result = subprocess.run(
            ["where" if platform.system() == "Windows" else "which", gradle_cmd],
            stdout=subprocess.PIPE,
            text=True
        )
        path = path_result.stdout.strip()

        # 解析版本
        version_line = [line for line in result.stdout.splitlines() if "Gradle" in line][0]
        version_match = re.search(r"Gradle (\d+\.\d+\.\d+)", version_line)
        if version_match:
            version = version_match.group(1)
        else:
            version = "未知版本"

        return (True, version, path, "Gradle环境正常")
    except Exception as e:
        return (False, "", "", f"Gradle检测异常: {str(e)}")

def get_environment_tools() -> list:
    """定义需要检测的命令行工具列表（移除了Android Studio）"""
    return [
        ("Java", check_java_environment, ENV_CONFIG["required"]["java"]["description"]),
        ("Android SDK", get_android_sdk_info, ENV_CONFIG["required"]["android_sdk"]["description"]),
        ("ADB (Platform Tools)", check_adb_environment, ENV_CONFIG["required"]["platform_tools"]["description"]),
        ("Gradle", check_gradle_environment, ENV_CONFIG["required"]["gradle"]["description"])
    ]

def check_command(tool_name: str, check_func, description: str) -> Tuple[bool, str, str, str]:
    """通用命令检测包装函数（仅检测存在性）"""
    try:
        result = check_func()
        # 处理不同检测函数的返回格式
        if tool_name == "Java" or tool_name == "ADB (Platform Tools)" or tool_name == "Gradle":
            # 返回格式：(是否成功, 版本, 路径, 消息)
            success, version, path, msg = result
            return (success, version, path, msg)
        else:
            # Android SDK返回字典格式
            info = result
            if isinstance(info, dict):
                if "error" in info:
                    return (False, "", "", info["error"])
                return (True, info.get("version", "未知版本"), info.get("path", "未知路径"), "检测正常")
            return (False, "", "", f"检测失败: {str(info)}")
    except Exception as e:
        return (False, "", "", f"检测异常: {str(e)}")